package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Grade;
import com.itheima.domain.Student;
import com.itheima.service.GradeService;
import com.itheima.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/grade")
public class GradeController {

    @Autowired
    private GradeService gradeService;
    @Autowired
    private StudentService studentService;

    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        int page = 1;
        int size = 5;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("size"))){
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = gradeService.findAll(page, size);
        request.setAttribute("page", all);
        return "/WEB-INF/pages/grade/grade-list.jsp";
    }

    @RequestMapping("/toEdit")
    public String toEdit(Integer gradeid, HttpServletRequest request){
        Grade grade = gradeService.findById(gradeid);
        request.setAttribute("grade", grade);
        return "/WEB-INF/pages/grade/grade-edit.jsp";
    }

    @RequestMapping(value="/update", method= RequestMethod.POST)
    public String update(@ModelAttribute("grade") Grade grade){
        gradeService.update(grade);
        return "/grade/findAll.action";
    }

    @RequestMapping("add")
    public String add(){
        return "/WEB-INF/pages/grade/grade-add.jsp";
    }

    @RequestMapping(value="/save", method= RequestMethod.POST)
    public String save(@ModelAttribute("grade") Grade grade){
        gradeService.save(grade);
        return "/grade/findAll.action";
    }

    @RequestMapping("/delete")
    public String delete(Integer gradeid){
        gradeService.delete(gradeid);
        return "/grade/findAll.action";
    }

    @RequestMapping("/showStudents")
    public String showStudents(Integer gradeid,HttpServletRequest request){
        List<Student> studentList = studentService.findByGradeid(gradeid);
        request.setAttribute("studentList", studentList);
        return "/WEB-INF/pages/grade/student-list.jsp";
    }

}
